package exmpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/*@WebServlet("/LoginServlet")*/
public class LoginServlet extends HttpServlet {
//    @Override
//    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setContentType("text/html;charset=UTF-8");
//        //主机
//        String host =req.getRemoteHost();
//        //端口号
//        int port = req.getServerPort();
//        //uri
//        String uri = req.getRequestURI();
//        //url
//        StringBuffer url = req.getRequestURL();
//        //协议
//        String protocol = req.getProtocol();
//
//        PrintWriter writer = resp.getWriter();
//        writer.println("主机:"+uri+",端口号:"+port+",uri:"+uri+",url:"+url+",协议:"+protocol);
//    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 获取表单参数
        String username = request.getParameter("username");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("_password");

//        System.out.println("用户名: " + username);
//        System.out.println("邮箱: " + email);
//        System.out.println("密码: " + password);
//        System.out.println("确认密码: " + confirmPassword);

        // 检查是否是注册请求
        if (username != null && email != null && password != null && confirmPassword != null) {
            // 处理注册逻辑
            if (!password.equals(confirmPassword)) {
                out.println("<script>alert('两次输入的密码不一致');window.location.href='register.html';</script>");
                return;
            }

            String jdbcUrl = "jdbc:mysql://localhost:3306/userdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
            String dbUser = "root";
            String dbPassword = "xx2468910.";

            try {
                // 加载 MySQL 驱动
                Class.forName("com.mysql.cj.jdbc.Driver");

                // 建立数据库连接
                Connection conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword);

                // 检查用户名是否已存在
                String checkUserSql = "SELECT * FROM users WHERE username = ? OR email = ?";
                PreparedStatement checkUserPs = conn.prepareStatement(checkUserSql);
                checkUserPs.setString(1, username);
                checkUserPs.setString(2, email);

                if (checkUserPs.executeQuery().next()) {
                    out.println("<script>alert('用户名或邮箱已存在');window.location.href='register.html';</script>");
                    return;
                }

                // 插入新用户
                String insertUserSql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
                PreparedStatement insertUserPs = conn.prepareStatement(insertUserSql);
                insertUserPs.setString(1, username);
                insertUserPs.setString(2, email);
                insertUserPs.setString(3, password);

                int rowsAffected = insertUserPs.executeUpdate();
                if (rowsAffected > 0) {
                    out.println("<script>alert('注册成功');window.location.href='login.html';</script>");
                } else {
                    out.println("<script>alert('注册失败');window.location.href='register.html';</script>");
                }

                // 关闭资源
                insertUserPs.close();
                checkUserPs.close();
                conn.close();
            } catch (ClassNotFoundException e) {
                out.println("<script>alert('数据库驱动未找到');window.location.href='register.html';</script>");
                e.printStackTrace();
            } catch (SQLException e) {
                out.println("<script>alert('数据库操作失败：" + e.getMessage() + "');window.location.href='register.html';</script>");
                e.printStackTrace();
            }
        } else {
            // 处理登录逻辑
            // ...
        }
    }
}
